package cn.client.ui.view.main.chat.friendApply

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.AlertDialog
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import cn.client.R
import cn.client.data.remoteData.bean.SearchFriend
import cn.client.data.remoteData.bean.SearchFriendRes
import cn.client.data.remoteData.bean.SendFriendApply
import coil.compose.AsyncImage

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SearchUserPage(
    userId: Int,
    navController: NavController,
    viewModel: FriendApplyViewModel = hiltViewModel()
    ){
    // 创建回调：接收item数据
    val context = LocalContext.current

    // 使用 collectAsState 来观察 ViewModel 中的 friendRes 状态
    val friendResState = viewModel.friendRes.collectAsState(initial = null)
    val friendResValue = friendResState.value

    var friendItemLook by remember { mutableStateOf(false) }

    LaunchedEffect(Unit){
        viewModel.pageEvents.collect {
            if (it is FriendApplyViewModel.PageEvent.Error){
                Toast.makeText(context,"错误：${it.error}", Toast.LENGTH_LONG).show()
            }
            if (it is FriendApplyViewModel.PageEvent.SearchFriend) {
                friendItemLook = !friendItemLook
                Toast.makeText(context,"搜索成功", Toast.LENGTH_LONG).show()
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(colorResource(R.color.LightGray01))
    ){
        TopAppBar(
            colors = TopAppBarDefaults.topAppBarColors(
                containerColor = MaterialTheme.colorScheme.primaryContainer,
                titleContentColor = MaterialTheme.colorScheme.primary),
            title = { Text("搜索用户") },
            /* 左边按钮 */
            navigationIcon = {
                IconButton( onClick = {
                /* 返回事件 */
                    navController.navigateUp()
                } ) { Icon(Icons.AutoMirrored.Filled.ArrowBack, null) } },
            /* 右边按钮（可以是多个） */
            actions = {
                IconButton(onClick = { /*   */ }
                ) { Icon(Icons.Filled.MoreVert, null) }
            })

        SearchUserBar(
            userId = userId,
            searchClickListener = object : SearchUserClickListener {
                override fun onSearchUserClicked(searchUser: SearchFriend){
                   //  发送搜索的意图
                    viewModel.dispatch(FriendApplyViewModel.PageIntent.SearchFriend(searchUser.uid, searchUser.account))
                }
            }
        )
        Spacer(modifier = Modifier.fillMaxWidth().height(20.dp))
        if (friendItemLook){
            Surface {
                SearchUserResItem(
                    userId = userId,
                    itemData = friendResValue!!,
                    sendApplyClickListener = object : SendFriendApplyClickListener {
                        override fun onSendFriendApplyClicked(sendFriendApply : SendFriendApply){
                            // 发送添加好友的意图
                            viewModel.dispatch(FriendApplyViewModel.PageIntent.SendFriendApply(sendFriendApply.uid, sendFriendApply.target, sendFriendApply.applyInfo))
                        }
                    })
            }
        }
    }
}
/**
 * 搜索用户的回调
 */
interface SearchUserClickListener {
    fun onSearchUserClicked(searchUser: SearchFriend)
}
/**
 * 发送好友申请
 */
interface SendFriendApplyClickListener {
    fun onSendFriendApplyClicked(sendFriendApply: SendFriendApply)
}

@Composable
fun SearchUserBar(
    userId: Int,
    searchClickListener: SearchUserClickListener
){
    var text by remember { mutableStateOf("") }    // 输入框

    Row(
        Modifier
            .fillMaxWidth()
            .background(colorResource(id = R.color.LightGray01), shape = RoundedCornerShape(2.dp))
            .height(60.dp)
            .padding(8.dp),
        verticalAlignment = Alignment.CenterVertically,
    ) {
        BasicTextField(
            value = text,
            onValueChange = { text = it },
            modifier = Modifier
                .background(Color.White, CircleShape)
                .weight(1f)
                .padding(start = 5.dp),
            textStyle = TextStyle(
                color = colorResource(id = R.color.DarkGray01),
                fontSize = 16.sp,
            ),
            decorationBox = { innerTextField ->
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    modifier = Modifier.padding(horizontal = 2.dp)
                ) {
                    IconButton( onClick = { /*  */ },
                    ) {
                        Icon(painterResource(id = R.drawable.ic_close_one),
                            null, tint = Color.White)
                    }
                    Box(
                        modifier = Modifier.weight(1f),
                        contentAlignment = Alignment.CenterStart
                    ) {
                        innerTextField()
                    }
                    IconButton(
                        onClick = {
                            /* 处理搜索的回调 */
                            searchClickListener.onSearchUserClicked(SearchFriend(uid = userId, account = text))
                        }
                    ) { Icon(imageVector = Icons.Default.Search, contentDescription = null) }
                }
            },
            keyboardActions = KeyboardActions(onSearch = {
            }),
            keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search)
        )
    }
}


@Composable
fun SearchUserResItem(
    userId: Int,
    itemData: SearchFriendRes,
    sendApplyClickListener: SendFriendApplyClickListener
){
    var showDialog by remember { mutableStateOf(false) }
    var applyInfo : String by remember { mutableStateOf("") }

    Row(
        modifier = Modifier
            .fillMaxWidth()
            .wrapContentHeight()
    ) {
        // 头像
        Row(
            modifier = Modifier
                .padding(5.dp)
                .clickable { /* TODO: */ }
        ){
            AsyncImage(
                model = itemData.avatar,
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .size(60.dp)
                    .clip(CircleShape)
            )
        }
        // 用户信息
        Column(
            modifier = Modifier
                .fillMaxWidth(0.75f)
                .wrapContentHeight()
                .padding(1.dp)
        ) {
            /* 用户名 */
            Row( modifier = Modifier.padding(1.dp) ){
                Text(text = "用 户：${itemData.uname}", fontSize = 14.sp) }
            /* 邮箱 */
            Row( modifier = Modifier.padding(1.dp) ){
                Text(text = "邮 箱：${itemData.email}", fontSize = 12.sp, color = Color.DarkGray) }
            /* 地区 */
            Row( modifier = Modifier.padding(1.dp) ){
                Text(text = "地 区：${itemData.area}", fontSize = 12.sp, color = Color.DarkGray) }
        }
        // 按钮
        Row( modifier = Modifier
            .wrapContentWidth()
            .wrapContentHeight()
            .padding(top = 7.dp)){
            TextButton(onClick = {
                /* 弹窗 */
                showDialog = !showDialog
            }) {
                Text(text = "添加好友")
            }
        }
    }

    if (showDialog) {
        AlertDialog(
            onDismissRequest = { showDialog = false },
            title = { Text(text = "添加好友") },
            text = {
                OutlinedTextField(
                    value = applyInfo,
                    onValueChange = { applyInfo = it },
                    modifier = Modifier.fillMaxWidth(),
                    visualTransformation = VisualTransformation.None,
                    maxLines = Int.MAX_VALUE, // 允许多行输入
                    singleLine = false
                )
            },
            buttons = {
                Row(modifier = Modifier.fillMaxWidth(),
                    /* 居右对齐 */
                    horizontalArrangement  = Arrangement.End ){
                    TextButton(
                        onClick = {
                            /* 发送好友申请的回调 */
                            val sendFriendApply = SendFriendApply(uid = userId, target = itemData.uid, applyInfo = applyInfo)
                            sendApplyClickListener.onSendFriendApplyClicked(sendFriendApply)
                            showDialog = false
                        }
                    ) {
                        Text(text = "确认")
                    }
                    Spacer(modifier = Modifier.width(8.dp))
                    TextButton(
                        onClick = {
                            // 取消逻辑
                            applyInfo = ""
                            showDialog = false
                        }
                    ) {
                        Text(text = "取消", color = Color.Gray)
                    }
                }
            }
        )
    }
}